<template>
  <div class="content">

    <el-button type="primary" @click="showCoordinateMap()">显示</el-button>

    <div class="mapBox">
      <CoordinateMap v-if="mapVisible" @getLnglat="getLnglat"></CoordinateMap>
    </div>

    <div>
      <!-- <el-upload class="oss-upload" 
                ref="upload1" 
                action=""
                :auto-upload="false" 
                :show-file-list="false" 
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                action:on-change="imgPreview" 
                list-type="picture"
      >
          <el-button size="small" type="primary">选择列表图</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
      </el-upload> -->
      <el-upload
        class="oss-upload"
        ref="upload1"
        action=""
        :multiple="true"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>

    
  </div>
</template>
<script>
import CoordinateMap from "@/components/map/CoordinateMap";

export default {
  components: {
    CoordinateMap
  },
  data() {
    return {
      mapVisible: false,

      fileList: [],

      sigData: {}
    };
  },
  created() {
    this.getSig();
  },
  mounted() {
    this.$ge.$on("map-close-finish", () => {
      this.mapVisible = false;
      // this.search();
    });
  },
  methods: {
    showCoordinateMap() {
      this.mapVisible = true;
    },
    getLnglat(lnglnt) {
      console.log('点击：', lnglnt)
    },

    getSig() {
      this.$get("/oss/getUploadOssSignature")
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.sigData = result.data
            console.log('sig', result.data)
          }
        })
        .catch((error) => {

        });
    },

    
    handlePreview(file) {
      console.log("点击文件列表中已上传的文件时的钩子")
      console.log(file);	
    },
    handleRemove(file, fileList) {
      console.log("文件列表移除文件时的钩子")
      console.log(file, fileList);
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      console.log("文件改变")
      console.log("file ", file)
      console.log("fileList ", fileList)
      //类型（jpg, png）和大小(2M 以内)
      const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isJPG) {
          this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
          return;
      }
      if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return;
      }
      if(isJPG && isLt2M) {
        this.fileList.push(file);
      }
      return false;
    },
    submitUpload() {
      console.log("上传")
      console.log(this.fileList)

      let fileObj = this.fileList[0];
      let data = this.sigData;//提前请求拿到的签名信息
      let ossData = new FormData()//创建oss数据对象
      ossData.append('name', fileObj.name)
      let picName = fileObj.name;
      let keyValue = '789/' + picName
      ossData.append('key', keyValue)
      ossData.append('policy', data.policy)
      ossData.append('OSSAccessKeyId', data.accessId)
      ossData.append('success_action_status', 200)
      ossData.append('Signature', data.signature)
      ossData.append('file', fileObj.raw)

      this.$postFormData(data.ossDomain, ossData)
      .then((result) => {
        console.log('上传结束 -- ', result)
      })
      .catch((error) => {

      });

      // let config = {
      //     headers: {
      //         "Content-Type": "application/json;charset=UTF-8"
      //     }
      // };
      // this.$axios
      //     .post('/up', ossData, config)
      //     .then(response => {
      //         console.log('上传结束 -- ', response)
      //     })
      //     .catch(err => {
      //         console.log('上传结束 异常-- ', err)
      //     });

    },
    //判断图片格式和大小
    // imgPreview(file) {
    //     if (file.status === "ready") {
    //         const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
    //         const isLt5M = file.raw.size / 1024 / 1024 < 2
    //         if (!isJPG) {
    //             this.$message.error('上传图片只能是 PNG、JPG 格式!')
    //             return false
    //         } else if (!isLt5M) {
    //             this.$message.error('上传图片大小不能超过2MB!')
    //             return false
    //         } else {
    //             //合适的图片会存入带上传图片数组
    //             this.fileList.push(file)
    //         }
    //     }
    // },
    //获取上传图片的名字
    // get_suffix(filename) {
    //     let pos = filename.lastIndexOf('.')
    //     let suffix = ''
    //     if (pos != -1) {
    //         suffix = filename.substring(pos)
    //     }
    //     return suffix
    // },
    //生成32位随机字符附在名字前面
    // random_string(len) {
    //     len = len || 32
    //     let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    //     let maxPos = chars.length
    //     let pwd = ''
    //     for (let i = 0; i < len; i++) {
    //         pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    //     }
    //     return pwd
    // },
    //图片上传拿签名
    picUpload(file,type) {
        let fileObj = file
        let data = this.upParams;//提前请求拿到的签名信息
        let ossData = new FormData()//创建oss数据对象
        ossData.append('name', fileObj.name)
        let filename = fileObj.name
        let picName = this.random_string(32) + this.get_suffix(filename)
        let keyValue = data.dir + picName
        if(type == 'list'){
            this.upList_picture.push(picName)
        }else if(type == 'detail'){
            this.upDetail_picture.push(picName)
        }
        ossData.append('key', keyValue)
        ossData.append('policy', data.policy)
        ossData.append('OSSAccessKeyId', data.accessid)
        ossData.append('success_action_status', 200)
        ossData.append('signature', data.signature)
        ossData.append('file', fileObj, fileObj.name)
    //实际项目中是将图片存在待上传列表中，点击确定后先进行上传，然后再把上传的图片信息发给后台保存，
    //这里的问题就是如果图片还没有上传成功就把数据发给后台的话，就会导致图片访问不到。
    //所以这里是通过返回一个promise，后面通过promise.all方法来判断是否全部上传成功。具体代码再下一个片段中
        return new Promise((resolve, reject) => {
            this.$http.post(data.host, ossData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
            }).then(res => {
                resolve(res);
            }).catch(error => {
                reject(error);
            })
        });
    }


  }
};
</script>
<style lang="sass" scoped>

</style>
